package com.wejoy.video.middle.station.data.util.weChat;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import com.wejoy.video.middle.station.data.exception.BusinessException;
import com.wejoy.video.middle.station.data.util.baiduevs.EvsApiHttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class WeChatUtils {

    private final static Logger logger = LoggerFactory.getLogger(EvsApiHttpUtils.class);

    private static final String CORPID="wwd9bc7c8b3bd31991";
    private static final String SECRET="dOdM18OvwT6K_hufAQZSOniFkndEIPocn8FrxHHNzZc";
    private static final Integer AGENTID=1000167;
    private static final String WECHAT_BASE_URL="https://wework.szgas.com.cn";
    private static final String WECHAT_GET_TOKEN_URL="/cgi-bin/gettoken";
    private static final String WECHAT_GET_DEPARTMENT_URL="/cgi-bin/department/list";
    private static final String WECHAT_GET_USER_URL="/cgi-bin/user/list";
    private static final String WECHAT_SEND_MESSAGE_URL="/cgi-bin/message/send?access_token={access_token}";

    public static HttpResponse postWithHeaders(String url, Map<String, String> headers, String requestBody) {
        HttpRequest request = HttpRequest.post(url)
                .headerMap(headers,false)
                .body(requestBody);
        HttpResponse execute = request.execute();
        if(!execute.isOk()){
            logger.error("请求微信接口失败");
        }
        return execute;
    }


    // 发送 GET 请求，并自定义请求头和参数
    public static HttpResponse getWithHeadersAndParams(String url, Map<String, String> headers, Map<String, Object> queryParams) {
        if (queryParams != null && !queryParams.isEmpty()) {
            StringBuilder urlBuilder = new StringBuilder(url);
            if (!url.contains("?")) {
                urlBuilder.append("?");
            } else {
                urlBuilder.append("&");
            }
            urlBuilder.append(buildQueryString(queryParams));
            url = urlBuilder.toString();
        }
        HttpRequest request = HttpRequest.get(url)
                .headerMap(headers, true);

        HttpResponse execute = request.execute();
        if (!execute.isOk()) {
            logger.error("请求微信接口失败");
        }
        return execute;
    }

    private static String buildQueryString(Map<String, Object> queryParams) {
        StringBuilder queryStringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
            if(entry.getValue()!=null){
                if (queryStringBuilder.length() > 0) {
                    queryStringBuilder.append("&");
                }
                queryStringBuilder.append(entry.getKey()).append("=").append(entry.getValue().toString());
            }
        }
        return queryStringBuilder.toString();
    }

    public static JSONObject getToken(){
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("corpid",CORPID);
        queryParams.put("corpsecret",SECRET);
        HttpResponse withHeadersAndParams = getWithHeadersAndParams(WECHAT_BASE_URL + WECHAT_GET_TOKEN_URL, null, queryParams);
        return JSONObject.parseObject(withHeadersAndParams.body());
    }

    public static JSONObject getDepartment(String token){
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("access_token",token);
        HttpResponse withHeadersAndParams = getWithHeadersAndParams(WECHAT_BASE_URL + WECHAT_GET_DEPARTMENT_URL, null, queryParams);
        return JSONObject.parseObject(withHeadersAndParams.body());
    }

    public static JSONObject getUserListByDepartment(String token,Integer departmentId,Integer fetchChild){
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("access_token",token);
        queryParams.put("department_id",departmentId);
        queryParams.put("fetch_child",fetchChild);
        HttpResponse withHeadersAndParams = getWithHeadersAndParams(WECHAT_BASE_URL + WECHAT_GET_USER_URL, null, queryParams);
        return JSONObject.parseObject(withHeadersAndParams.body());
    }


    public static JSONObject sendMessage(String token,String userIds,String content){
        JSONObject params = new JSONObject();
        params.put("touser",userIds);
        params.put("msgtype","text");
        params.put("agentid",AGENTID);
        JSONObject contentJson = new JSONObject();
        contentJson.put("content",content);
        params.put("text",contentJson);
        HttpResponse withHeadersAndParams = postWithHeaders(WECHAT_BASE_URL + WECHAT_SEND_MESSAGE_URL.replace("{access_token}",token), null,params.toJSONString());
        return JSONObject.parseObject(withHeadersAndParams.body());
    }

//    public static void main(String[] args) {
//        String token="QbG3sPDtKWQgtWl9iTIOQsnLUtrrnYtjtA_iBPuSPxc0YALMK6f0sLdj6uPkb5ZIFCxL11f6AzxQ3Mh5ykzk-9EDY0mKz3x5R6xkokpVeto-9oMfdz6XdSljW2XBcfiK8qrKrhlfwL2i11-wGP5MNUZJMOdxuw_y8LQIJnp0mT6aPFK77hOun69pK2QlSPmMq03ViwVu6tybLVHOo9dNU_h6I5p_Vug1TWZegHkpO5k";
//
////        JSONObject token = getToken();
////        System.out.println(token);
////        System.out.println(getDepartment(token.));
////        System.out.println(getUserListByDepartment(token,2137105112,0));
//        System.out.println(sendMessage(token, "jk_yxd",
//                "您有1条 三十埠母站 的监控预警信息未处理，请前往<a href=\\\"http://miw.szgas.com.cn:8080/#/pages/order/order\\\">监控预警</a>查看详细"));
//
//
////        System.out.println(getUserListByDepartment(token,2137105110,0));
//    }


}